package com.woniu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.PageResult;
import com.woniu.entity.Result;
import com.woniu.vo.SearchCriteria;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.woniu.pojo.PackageRecord;
import com.woniu.service.IPackageRecordService;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务包操作记录 前端控制器
 * </p>
 *
 * @author YMY
 * @since 2022-10-12
 */
@Api(tags = "服务包操作历史记录")
@RestController
@RequestMapping("/package-record")
    public class PackageRecordController extends BaseController{

        @Autowired
        private IPackageRecordService packageRecordService;

        @ApiOperation("查询所有服务包历史记录")
        @GetMapping
        public Result queryAll(){
            List<PackageRecord> packageRecordList = packageRecordService.list();

            return toDataResult(packageRecordList) ;

        }

        @ApiOperation("增加服务包的历史操作")
        @PostMapping
        public Result add(@RequestBody PackageRecord packageRecord){
            packageRecord.setTime(LocalDateTime.now());

            return toResult(packageRecordService.save(packageRecord));

        }




        @ApiOperation("条件分页查询")
        @PostMapping("/search/{page}/{size}")
        public Result search(@PathVariable int page, @PathVariable int size, @RequestBody SearchCriteria searchCriteria){
            IPage<PackageRecord> p=new Page<PackageRecord>(page,size);
            QueryWrapper<PackageRecord> wrapper=new QueryWrapper<>();
            if(searchCriteria.getName()!=null)wrapper.like("name",searchCriteria.getName());
            if(searchCriteria.getStartTime()!=null)wrapper.gt("create_time",searchCriteria.getStartTime());
            if(searchCriteria.getEndTime()!=null)wrapper.lt("create_time",searchCriteria.getEndTime());
            if(searchCriteria.getOther()!=null&&searchCriteria.getOther().size()>0){
                searchCriteria.getOther().forEach((key,value)->{
                wrapper.eq(key,value);
                });
            }
            if(searchCriteria.getOtherLike()!=null&&searchCriteria.getOtherLike().size()>0){
                searchCriteria.getOtherLike().forEach((key,value)->{
                wrapper.like(key,value);
                });
            }

            p = packageRecordService.page(p, wrapper);
            PageResult pageResult=new PageResult();
            List<PackageRecord> records = p.getRecords();
            records.sort((r1,r2)->r2.getTime().compareTo(r1.getTime()));

            pageResult.setData(records);
            pageResult.setTotal(p.getTotal());

            return toDataResult(pageResult);
        }





        }

